package com.iwhalecloud.bss.kite.cucc.web.service.accept.util;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts2;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.dataservice.entity.fee.ShowRule;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneAdditionalOfferInstService;
import com.iwhalecloud.bss.kite.client.dto.inst.InstAttrDTO;
import com.iwhalecloud.bss.kite.client.dto.inst.OfferInstDTO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteMapUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.offer.CategoryOfferDTO;
import com.iwhalecloud.bss.kite.cucc.client.service.cache.ILocalRefreshCacheService;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.CuccOfferVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.CuccPayAddtionOfferVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.CuccProdSubOfferVO;
import com.iwhalecloud.bss.kite.cucc.client.vo.scene.WholeQuickEntryVO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.util.DateFormatUtils;
import com.iwhalecloud.bss.kite.cucc.common.util.DateUtils;
import com.iwhalecloud.bss.kite.cucc.dataservice.cache.CategoryOfferCache;
import com.iwhalecloud.bss.kite.cucc.service.cache.LocalWholeQuickEntryCache;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferAttrCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferDetailCache;
import com.iwhalecloud.bss.kite.dataservice.cache.OfferFeeDiscntShowRuleCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProdFeeCache;
import com.iwhalecloud.bss.kite.dataservice.cache.ProductCache;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.dataservice.entity.OfferAttr;
import com.iwhalecloud.bss.kite.dataservice.entity.fee.OfferFeeDiscntShowRule;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.Offer;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferDetail;
import com.iwhalecloud.bss.kite.dataservice.entity.spec.OfferRelInfo;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.enums.InstType;
import com.iwhalecloud.bss.kite.manager.enums.RelType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteOfferInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.ztesoft.bss.base.staticdata.CoreDataOffer;
import com.ztesoft.bss.common.util.SpringUtil;

/**
 * <Description>可选包处理 <br>
 *
 * @see com.iwhalecloud.bss.kite.web.service.accept.util <br>
 * @since R9.0<br>
 */
@Service
public class LocalAdditionalOfferUtils {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private OperateInstAttrService operateInstAttrService;

    @Autowired
    private IOperateSceneAdditionalOfferInstService operateSceneAdditionalOfferInstService;

    @Autowired
    IOperateSceneInstService sceneInstOperateService;
    public final static String OFFERINSTIDS = "additionalOfferInstIds";
    public final static String PEIZHIFEIYONG = "peizhifeiyong";
    public final static String XIEYIJIA = "xieyijia";
    public final static String ZHEKOU = "zhekou";
    public final static String PKEY = "qcxyjkjlr";
    //全程协议价资费限制
    public final static List<String> fieldNames = Arrays.asList("200000170", "200000171", "200000172", "200000173", "200000174","200000169");

    public static LocalAdditionalOfferUtils getInst() {
        return SpringUtil.getBean(LocalAdditionalOfferUtils.class);
    }

    /**
     * 构造可选包对象
     *
     * @param offerInst 可选包实例
     * @param prodId    接入产品标识
     * @param roleId    接入产品角色标识
     * @return
     */
    public CuccProdSubOfferVO genProdSubOfferVO(OfferInstDTO offerInst, String prodId, String roleId) {
        Offer offer = OfferCache.get(offerInst.getOfferId());
        CuccProdSubOfferVO prodSubOfferVO = new CuccProdSubOfferVO();
        prodSubOfferVO.setOfferName(offer.getOfferName());
        prodSubOfferVO.setOfferId(offerInst.getOfferId());
        prodSubOfferVO.setOfferType(offer.getOfferType());
        prodSubOfferVO.setOfferInstId(offerInst.getOfferInstId());
        prodSubOfferVO.setActionType(offerInst.getActionType());
        if (KiteListUtils.isEmpty(offerInst.getInstAttrDTOS())) {
            prodSubOfferVO.setRstrAttr(false);
        } else {
            prodSubOfferVO.setRstrAttr(true);
        }
        prodSubOfferVO.setRstrFee(false);
        prodSubOfferVO.setRstrMktRes(isRstrMktRes(offer, prodId, roleId));
        prodSubOfferVO.setStatus(offer.getStatusCd());
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        List<InstAttrDTO> instAttrDTOList = dealBillAttr(offerInst.getInstAttrDTOS(), sceneInstId, querySceneInstService.getOfferInst(sceneInstId, offerInst.getOfferInstId()));
        prodSubOfferVO.setInstAttrDTOS(instAttrDTOList);
        return prodSubOfferVO;
    }


    private List<InstAttrDTO> dealBillAttr(List<InstAttrDTO> instAttrList, String sceneInstId, KiteOfferInst kiteOfferInst) {
        Map<String, Integer> sortMap = getSortMap();
        List<InstAttrDTO> feeAttrList = new ArrayList<>();
        instAttrList.forEach(instAttrDTO -> {
            String fieldName = instAttrDTO.getFieldName();
            if (sortMap.containsKey(fieldName)) {
                instAttrDTO.setIsEdit("F");
                if ("200000172".equals(fieldName)) {
                    String startDate = DateUtils.formatDate(DateUtils.getStartOfDay(), DateUtils.DEFAULT_PATTERN);
                    instAttrDTO.setValue(startDate);
                    instAttrDTO.setValueDesc(startDate);
                } else if ("200000173".equals(fieldName)) {
                    String endDate = DateUtils.formatDate(DateUtils.getEndOfDay(), DateUtils.DEFAULT_PATTERN);
                    instAttrDTO.setValue(endDate);
                    instAttrDTO.setValueDesc(endDate);
                }
                if (StringUtils.isEmpty(instAttrDTO.getValue())) {
                    String value = instAttrDTO.getValue();
                    String valueDesc = instAttrDTO.getValueDesc();
                    if ("200001648".equals(fieldName)) {
                        KiteOfferInst offerInst = querySceneInstService.getMainOfferInst(sceneInstId);
                        List<OfferAttr> offerAttrs = OfferAttrCache.get(offerInst.getOfferId());
                        for (OfferAttr offerAttr : offerAttrs) {
                            if ("price".equals(offerAttr.getFieldName())) {
                                value = offerAttr.getDefaultValue();
                                valueDesc = value;
                                break;
                            }
                        }

                    } else if ("200000172".equals(fieldName)) {
                        value = DateUtils.formatDate(DateUtils.getStartOfDay(), DateUtils.DEFAULT_PATTERN);
                        valueDesc = value;
                    } else if ("200000173".equals(fieldName)) {
                        value = DateUtils.formatDate(DateUtils.getEndOfDay(), DateUtils.DEFAULT_PATTERN);
                        valueDesc = value;
                    } else if (KeyConsts.DROPDOWN.equals(instAttrDTO.getAttrValueTypeId()) && KiteListUtils.isNotEmpty(instAttrDTO.getAttrValues())) {
                        value = instAttrDTO.getAttrValues().stream().filter((attr) -> !KiteStringUtils.isEmpty(attr.getAttrValue())).collect(Collectors.toList()).get(0).getAttrValue();
                        valueDesc = instAttrDTO.getAttrValues().stream().filter((attr) -> !KiteStringUtils.isEmpty(attr.getAttrValue())).collect(Collectors.toList()).get(0).getAttrValueDesc();
                    }
                    instAttrDTO.setValue(value);
                    instAttrDTO.setValueDesc(valueDesc);

                    operateInstAttrService.setAttrValue(kiteOfferInst, fieldName, value, sceneInstId, null);
                }
                feeAttrList.add(instAttrDTO);
            }
        });

        return feeAttrList;
    }

    public void setWholeQuickEntryVO(List<CuccPayAddtionOfferVO> cuccPayAddtionOfferVOList, String sceneInstId, Integer checked) {

        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        List<String> serviceOfferIds = querySceneInstService.getExtParameterValue(sceneInstId,"BUSI_CHANGE_SERVICEOFFERID");
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String custId = KiteWebContext.getContext().getCustId();
        KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, kiteSceneInst.getRootInstId());
        CuccPayAddtionOfferVO payAddtionOfferVO = null;
        for (CuccPayAddtionOfferVO vo : cuccPayAddtionOfferVOList) {
            if (null != vo.getWholeQuickEntryVO()) {
                payAddtionOfferVO = vo;
            }
        }


        if (kiteSceneInst.getServiceOfferId().equals("2826")) {
            if(!serviceOfferIds.contains("1009")){
                for (CuccPayAddtionOfferVO vo : cuccPayAddtionOfferVOList) {
                    vo.setWholeQuickEntryVO(null);
                }
                return;
            }
        }
        String cateId = Optional.ofNullable(offerInst.getAttrValue("cateId")).orElse("");
//        if (KiteStringUtils.equalsAny(cateId, ProdCateUtil.getCateIdByCodeForArr(ProdCateUtil.SDH_CODE))) {
//            return;
//        }
        if (null == payAddtionOfferVO || null == payAddtionOfferVO.getOfferVOList() || null == payAddtionOfferVO.getOfferVOList().get(0) || null == payAddtionOfferVO.getOfferVOList().get(0).getOfferInst() || null == payAddtionOfferVO.getOfferVOList().get(0).getOfferInst().get(0)) {
            return;
        }
        Map<String, KiteAttr> kiteAttrMap = payAddtionOfferVO.getOfferVOList().get(0).getOfferInst().get(0).getAttrMap();
        if (null == kiteAttrMap || kiteAttrMap.size() == 0) {
            return;
        }
        List<DcPublic> zf = DcPublicCache.getByPkey(offerInst.getSpecId(), PKEY);
        List<DcPublic> dcPublicList = DcPublicCache.getByPkey(cateId, PKEY);

        List<KiteAttr> kiteAttrList = new ArrayList<>();
        WholeQuickEntryVO wholeQuickEntryVO = null;
        if (KiteListUtils.isNotEmpty(dcPublicList)) {
            List<String> ratioList = new ArrayList<>();
            String configCost = count(payAddtionOfferVO, ratioList);
            dcPublicList.forEach(dcPublic -> {
                KiteAttr kiteAttr = new KiteAttr();
                kiteAttr.setAttrValueTypeId(dcPublic.getCodec());
                kiteAttr.setIsNull(dcPublic.getCodea());
                kiteAttr.setIsEdit(dcPublic.getCodeb());
                kiteAttr.setShowType(dcPublic.getCoded());
                kiteAttr.setValue("");
                kiteAttr.setValueDesc("");
                kiteAttr.setCname(dcPublic.getPname());
                kiteAttr.setFieldName(dcPublic.getPcode());
                kiteAttr.setOrderId(dcPublic.getSortby());
                if (dcPublic.getPcode().equals(PEIZHIFEIYONG)) {
                    kiteAttr.setValue(configCost);
                }
                if (configCost.equals(StringUtils.EMPTY)) {
                    if (KiteStringUtils.equalsAny(dcPublic.getPcode(), ZHEKOU, XIEYIJIA)) {
                        kiteAttr.setIsNull("T");
                    }
                }
                if (dcPublic.getCodec().equals("98A")) {
                    KiteAttr ka = kiteAttrMap.get(dcPublic.getPcode());
                    if (null != ka) {
                        List<KiteAttrValue> attrValues = ka.getAttrValues();
                        List<KiteAttrValue> attrValueNew = new ArrayList<>();
                        attrValues.forEach(attrValue -> {
                            KiteAttrValue kiteAttrValue = new KiteAttrValue();
                            BeanUtils.copyProperties(attrValue, kiteAttrValue);
                            attrValueNew.add(kiteAttrValue);
                        });
                        kiteAttr.setAttrValues(attrValueNew);
                        if (kiteAttrMap.get(dcPublic.getPcode()).getValue() != null) {
                            kiteAttr.setValue(kiteAttrMap.get(dcPublic.getPcode()).getValue());
                            kiteAttr.setValueDesc(kiteAttrMap.get(dcPublic.getPcode()).getValueDesc());
                        }
                    }
                }
                if (dcPublic.getCodec().equals("98D") && kiteAttrMap.get(dcPublic.getPcode()).getValue() != null) {
                    kiteAttr.setValue(kiteAttrMap.get(dcPublic.getPcode()).getValue());
                    kiteAttr.setValueDesc(kiteAttrMap.get(dcPublic.getPcode()).getValueDesc());
                }
                kiteAttrList.add(kiteAttr);
            });
            wholeQuickEntryVO = payAddtionOfferVO.getWholeQuickEntryVO();
            wholeQuickEntryVO.setKiteAttrs(kiteAttrList);
            wholeQuickEntryVO.setRatio(ratioList);
            wholeQuickEntryVO.setType(0);
            //设置选中属性
            if (null != checked) {
                if (checked == 1) {
                    payAddtionOfferVO.getOfferVOList().forEach(cuccOfferVO -> {
                        //置灰处理
                        if (null != cuccOfferVO.getOfferInst() && cuccOfferVO.getOfferInst().size() > 0) {
                            for (String fieldName : fieldNames) {
                                if (null != cuccOfferVO.getOfferInst().get(0).getAttrMap().get(fieldName)) {
                                    cuccOfferVO.getOfferInst().get(0).getAttrMap().get(fieldName).setIsEdit("F");
                                }
                            }
                        }
                    });
                }
                wholeQuickEntryVO.setChecked(checked);
            } else {
                wholeQuickEntryVO.setChecked(0);
            }

            wholeQuickEntryVO.setWholeQuickEntryId(sceneInstId);
        }
        List<String> offerInstIds = payAddtionOfferVO.getOfferVOList().stream().filter(vo -> (Objects.nonNull(vo.getOfferInst()) && vo.getOfferInst().size() > 0)).map(vo -> {
            return vo.getOfferInst().get(0).getInstId();
        }).collect(Collectors.toList());
        sceneInstOperateService.putExtParameter(sceneInstId, OFFERINSTIDS, offerInstIds);
        LocalWholeQuickEntryCache.put(sceneInstId, wholeQuickEntryVO);
    }

    private Map<String, Integer> getSortMap() {
        //单价 生效时间 失效时间 生效模式 失效模式
        Map<String, Integer> sortMap = new HashMap<>();
        sortMap.put("200001648", 1);
        sortMap.put("200000172", 2);
        sortMap.put("200000173", 3);
        sortMap.put("200000174", 4);
        sortMap.put("200001735", 5);
        return sortMap;
    }


    /**
     * 是否有终端
     *
     * @param offer  可选包规格
     * @param prodId 接入产品标识
     * @param roleId 接入产品角色标识
     * @return
     */
    public boolean isRstrMktRes(Offer offer, String prodId, String roleId) {
        return false;
    }

    /**
     * 构造可选包对象
     *
     * @param offerInsts 可选包实例列表
     * @param prodId     接入产品标识
     * @param roleId     接入产品角色标识
     * @return
     */
    public List<CuccProdSubOfferVO> transferProdSubOfferVO(List<OfferInstDTO> offerInsts, String prodId, String roleId) {
        return offerInsts.stream().map(offerInstDTO -> genProdSubOfferVO(offerInstDTO, prodId, roleId))
            .collect(Collectors.toList());
    }

    /**
     * 设置type
     *
     * @param additionalOfferInstList    可选包实例
     * @param productAdditionalOfferList 挂在产品上面的可选包规格
     * @return
     */
    public void setType(List<CuccProdSubOfferVO> additionalOfferInstList, List<Offer> productAdditionalOfferList) {
        for (CuccProdSubOfferVO offerInst : additionalOfferInstList) {
            if (isContainSubOffer(productAdditionalOfferList, offerInst.getOfferId())) {
                offerInst.setType(KeyConsts.ADDITIONAL_PRODUCT_TYPE);
            } else {
                offerInst.setType(KeyConsts.ADDITIONAL_OFFER_TYPE);
            }
            Offer offer = OfferCache.get(offerInst.getOfferId());
            if (Objects.nonNull(offer)) {
                offerInst.setStatus(offer.getStatusCd());
            }
        }
    }

    /**
     * 是否包含指定的可选包
     *
     * @param offers  可选包列表
     * @param offerId 可选包标识
     * @return
     */
    public boolean isContainSubOffer(List<Offer> offers, String offerId) {
        if (!KiteListUtils.isEmpty(offers)) {
            for (Offer offer : offers) {
                if (offer.getOfferId().equals(offerId)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 构造可选包页面对象
     *
     * @param offerInstList
     * @param prodId
     * @param roleId
     * @return
     */
    public List<CuccProdSubOfferVO> getProdSubOfferList(List<OfferInstDTO> offerInstList, String prodId, String roleId) {
        List<CuccProdSubOfferVO> resultOfferList = new ArrayList<>();
        if (!KiteListUtils.isEmpty(offerInstList)) {
            resultOfferList = transferProdSubOfferVO(offerInstList, prodId, roleId);
            //挂在产品上面的必选可选包
            final List<Offer> productMustAdditionalOffers = OfferCache.get(ProductCache.get(prodId).getBaseOfferId())
                .listMustAdditionalOffers();
            //挂在产品上面的默选可选包
            final List<Offer> productDefaultAdditionalOffers = OfferCache.get(ProductCache.get(prodId).getBaseOfferId())
                .listDefaultAdditionalOffers();
            List<Offer> productAdditionalOfferList = new ArrayList<>();
            productAdditionalOfferList.addAll(productMustAdditionalOffers);
            productAdditionalOfferList.addAll(productDefaultAdditionalOffers);
            //产品的所有可选包
            productAdditionalOfferList.addAll(OfferCache.get(ProductCache.get(prodId).getBaseOfferId()).listAllZOffers());

            //设置type
            setType(resultOfferList, productAdditionalOfferList);
        }
        return resultOfferList;
    }

    /**
     * 构造可选类型可选包 -- 不加载实例化信息
     *
     * @return
     */
    public List<CuccPayAddtionOfferVO> getOptionalAdditionalOfferListWithOutInst(String sceneInstId, String custId, String offerInstId, String staffId, int checked, String feeTypeCode) {
        //如果已经实例化，可能在录入页属性联动实例化，则将实例化的对象包括属性一起返回加载展示
        List<CuccPayAddtionOfferVO> cuccPayAddtionOfferVOList = new ArrayList<>();
        KiteOfferInst offerInst = querySceneInstService.getOfferInst(custId, offerInstId);
        if (KiteObjectUtils.isEmpty(offerInst)) {
            return cuccPayAddtionOfferVOList;
        }
        KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
        //查询所有的可选包规格
        List<OfferRelInfo> offerRelInfoList = OfferCache.get(offerInst.getOfferId()).listAllOfferRels().stream().filter(offerRelInfo -> {
            return CoreDataOffer.OFF_0005_12.equals(offerRelInfo.getzOfferType()) && StringUtils.equalsAny(offerRelInfo.getRelType(), CoreDataOffer.OFF_0006_100000, CoreDataOffer.OFF_0006_120000);
        }).collect(Collectors.toList());
        KiteProdInst kiteProdInst = querySceneInstService.listProdInstsFromOfferInst(custId, offerInstId).get(0);
        this.filterFeeByAttr(offerRelInfoList, kiteProdInst.listAttrs(), offerInst.getOfferId());
        //SpringUtil.getBean(ILocalRefreshCacheService.class).refreshOffer(offerInst.getOfferId());
        List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");
        String stopRatioAttrValue = querySceneInstService.getCommonAttrValue(sceneInstId, "STOP_RATIO");
        String recoverRatioAttrValue = querySceneInstService.getCommonAttrValue(sceneInstId, "RECOVER_RATIO");
        List<DcPublic> defaultControl = DcPublicCache.getByPkey(offerInst.getSpecId(), PKEY);

        // 以太网国际产品，是否显示：数字电路-拆分管理费（产品编码：63249047）
        boolean ytwgjFlag = true;
        String catagoryId = Optional.ofNullable(OfferCache.get(offerInst.getOfferId())).map(Offer::getCateId).orElse(null);
        if (KiteStringUtils.equalsAny(catagoryId, "2101140", "2101142", "2101141")) {
            // 资源组织方式（100005334：只提供国际全电路；100005332：国内延伸电路+国际全电路+境外延伸电路；100005331：国内延伸电路+国际全电路）
            String resourceOrganization = kiteProdInst.getAttrValue("200003235");
            // 是否带宽批发业务（110007573：小带宽）
            String isBandwidthWholesale = kiteProdInst.getAttrValue("210004528");
            ytwgjFlag = KiteStringUtils.isEqual(isBandwidthWholesale, "110007573") && KiteStringUtils.equalsAny(resourceOrganization, "100005334", "100005332", "100005331");
        }
        boolean _ytwgjFlag = ytwgjFlag;

        offerRelInfoList.forEach(offerRelInfo -> {
            Offer additionalOffer = ProdFeeCache.get(offerRelInfo.getzOfferId());
            if (Objects.isNull(additionalOffer)) {
                SpringUtil.getBean(ILocalRefreshCacheService.class).refreshAdditionalOfferCache(offerInst.getOfferId());
                additionalOffer = ProdFeeCache.get(offerRelInfo.getzOfferId());
            }
            // 获取此规格下已存在的可选包实例
            List<KiteOfferInst> additionalInstList = querySceneInstService
                .listOfferInstsByProdInstId(custId, kiteProdInst.getProdInstId(), InstType.ADDITIONAL_OFFER_INST,
                    offerRelInfo.getzOfferId());
            additionalInstList.removeIf(
                additionalInst -> KiteStringUtils.equals(additionalInst.getActionType().name(), ActionType.D.name()));
            //失效资费不能再订购
            if (KiteStringUtils.equals(offerRelInfo.getStatusCd(), KeyConsts2.PROD_STATUS_HIS_00C)) {
                return;
            }
            CuccOfferVO offerVO = KiteBeanUtils.transform(additionalOffer, CuccOfferVO.class);
            Map<String, Object> offerMap = additionalOffer.getOfferMap();
            if (KiteMapUtils.isNotEmpty(offerMap)) {
                String saleProvince = KiteMapUtils.getString(offerMap, "saleProvince");
                if (KiteStringUtils.isNotEmpty(saleProvince) && !KiteStringUtils.isIndexOf(saleProvince, "09", ",")
                    && !KiteStringUtils.isIndexOf(saleProvince, sceneInst.getProvinceNbr(), ",")) {
                    return;
                }
                // 停复机场景仅展示停机保号费,其他场景不展示
                if ("1003".equals(stopRatioAttrValue) || KiteStringUtils.equalsAny(recoverRatioAttrValue, "1004", "1048")) {
                    if (!LocalKeyConsts.FEE_PAY_TYPE_SHUTDOWN_NUMBER.equals(KiteMapUtils.getString(offerMap, "payType"))) {
                        return;
                    }
                } else {
                    if (LocalKeyConsts.FEE_PAY_TYPE_SHUTDOWN_NUMBER.equals(KiteMapUtils.getString(offerMap, "payType"))) {
                        return;
                    }
                }
                if (LocalKeyConsts.FEE_PAY_TYPE_ONE_OFF.equals(KiteMapUtils.getString(offerMap, "payType")) && !CuccPosServiceUtils.showAndEditOneOffAddionalOffer(sceneInstId)) {
                    return;
                }
                offerVO.setPayType(KiteMapUtils.getString(offerMap, "payType"));
            }

            // 五大双线基础产品（不包括落地方、收费方产品）
            if (ProdCateUtil.getDoubleLineOfferId().contains(offerInst.getOfferId())) {
                // 发起方资费、收费方资费，只返回查询的类型
                String thisFeeTypeCode = KiteStringUtils.equalsAny(offerVO.getPayType(), "monthly-charge", "one-time-charge") ? "2" : "1";
                if (!KiteStringUtils.isEqual(thisFeeTypeCode, feeTypeCode)) {
                    return;
                }
            }

            if (!_ytwgjFlag && KiteStringUtils.isEqual(offerVO.getOfferId(), "63249047")) {
                return;
            }

            boolean isOwe = false;
            //资费产品分组
            CategoryOfferDTO categoryOffer = CategoryOfferCache.get(offerVO.getOfferId());

            if (!KiteObjectUtils.isEmpty(categoryOffer)) {
                String minMun = categoryOffer.getMinNum();
                String maxMun = categoryOffer.getMaxNum();

                // 最大值和最小值一样，则创建可选包实例
                if (KiteStringUtils.isNotEmpty(minMun) && KiteStringUtils.isNotEmpty(maxMun) && Integer.valueOf(maxMun) > 0 && KiteStringUtils.isEqual(minMun, maxMun)) {
                    //全程协议价控制默认选中
                    if (checked == 1) {
                        if (null != defaultControl && defaultControl.size() > 0 && (defaultControl.get(0).getCodee().contains(additionalOffer.getOfferId()) || KiteStringUtils.equalsAny(additionalOffer.getOfferId(), defaultControl.get(0).getCodea(), defaultControl.get(0).getCodeb(), defaultControl.get(0).getCodec(), defaultControl.get(0).getCoded()))) {
                            setOfferInst(sceneInstId, offerInstId, kiteProdInst, additionalOffer, custId, staffId, offerVO);
                        }
                    } else {
                        setOfferInst(sceneInstId, offerInstId, kiteProdInst, additionalOffer, custId, staffId, offerVO);
                    }
                } else if (KiteStringUtils.isNotEmpty(minMun) && KiteStringUtils.isNotEmpty(maxMun) && Integer.valueOf(maxMun) > 0 && !KiteStringUtils.isEqual(minMun, maxMun)) {
                    if (checked == 1) {
                        if (null != defaultControl && defaultControl.size() > 0 && (defaultControl.get(0).getCodee().contains(additionalOffer.getOfferId()) || KiteStringUtils.equalsAny(additionalOffer.getOfferId(), defaultControl.get(0).getCodea(), defaultControl.get(0).getCodeb(), defaultControl.get(0).getCodec(), defaultControl.get(0).getCoded()))) {
                            setOfferInst(sceneInstId, offerInstId, kiteProdInst, additionalOffer, custId, staffId, offerVO);
                        }
                    }
                }
                // 河南互联网是否云网络加速属性，如果选择是，则云网络加速资费默认勾选
                else if (KiteStringUtils.equals("100000000016992", categoryOffer.getOfferId())
                    && KiteStringUtils.equals("1_0000106", kiteProdInst.getAttrValue("200004193"))) {
                    OfferInstDTO offerInstDTO = operateSceneAdditionalOfferInstService
                        .addAdditionalOffer(sceneInstId, offerInstId, kiteProdInst.getProdInstId(), additionalOffer.getOfferId(), custId, staffId).getResultObject();

                    //处理可选包与产品实例之间的关系，因后续的明细处理事件的max不可控，可能导致没添加关系
                    OfferDetail additionalOfferDetail = OfferDetailCache.get(offerInstDTO.getOfferId()).stream().filter(offerDetail -> {
                        return offerDetail.getObjId().equals(kiteProdInst.getProdId());
                    }).findFirst().orElse(null);
                    if (!KiteObjectUtils.isEmpty(additionalOfferDetail)) {

                        sceneInstOperateService.addOfferObjInstRel(sceneInstId, InstType.ADDITIONAL_OFFER_INST, offerInstDTO.getOfferInstId(),
                            kiteProdInst.getInstType(), kiteProdInst.getProdInstId(), RelType.OFFER_OBJ_REL_TYPE_1000, ActionType.A,
                            additionalOfferDetail.getRoleId(), additionalOfferDetail.getDetailId(), KiteWebContext.getContext().getCustId());
                    }
                    KiteOfferInst additionalOfferInst = querySceneInstService.getOfferInst(custId, offerInstDTO.getOfferInstId());

                    offerVO.setOfferInst(Collections.singletonList(additionalOfferInst));
                }


                if (filterOfferVoByKeyAttr(offerVO, kiteProdInst, offerInstId, sceneInstId, staffId, serviceOfferIdList, offerRelInfo.getaOfferId())) {
                    for (CuccPayAddtionOfferVO cuccPayAddtionOfferVO : cuccPayAddtionOfferVOList) {
                        if (cuccPayAddtionOfferVO.getCategoryId().equals(categoryOffer.getCategoryId())) {
                            isOwe = true;
                            cuccPayAddtionOfferVO.getOfferVOList().add(offerVO);
                            if (null != defaultControl && defaultControl.size() > 0 && KiteStringUtils.equalsAny(categoryOffer.getOfferId(), defaultControl.get(0).getCodea(), defaultControl.get(0).getCodeb(), defaultControl.get(0).getCodec(), defaultControl.get(0).getCoded())) {
                                cuccPayAddtionOfferVO.setWholeQuickEntryVO(new WholeQuickEntryVO());
                                cuccPayAddtionOfferVO.getWholeQuickEntryVO().setChecked(checked);
                            }
                        }
                    }

                    if (!isOwe) {
                        CuccPayAddtionOfferVO cuccPayAddtionOfferVO = new CuccPayAddtionOfferVO();
                        cuccPayAddtionOfferVO.setCategoryId(categoryOffer.getCategoryId());
                        cuccPayAddtionOfferVO.setCateName(categoryOffer.getCateName());
                        cuccPayAddtionOfferVO.setMaxNum(categoryOffer.getMaxNum());
                        cuccPayAddtionOfferVO.setMinNum(categoryOffer.getMinNum());
                        cuccPayAddtionOfferVO.getOfferVOList().add(offerVO);
                        if (null != defaultControl && defaultControl.size() > 0 && KiteStringUtils.equalsAny(categoryOffer.getOfferId(), defaultControl.get(0).getCodea(), defaultControl.get(0).getCodeb(), defaultControl.get(0).getCodec(), defaultControl.get(0).getCoded())) {
                            cuccPayAddtionOfferVO.setWholeQuickEntryVO(new WholeQuickEntryVO());
                            cuccPayAddtionOfferVO.getWholeQuickEntryVO().setChecked(checked);
                        }
                        cuccPayAddtionOfferVOList.add(cuccPayAddtionOfferVO);
                    }
                }
            }
        });
        sortOfferList(cuccPayAddtionOfferVOList);
        // 批量受理需求：不展示趸交资费oneOffFees
        if (CuccPosServiceUtils.isBatchAccept(sceneInstId)) {
            cuccPayAddtionOfferVOList.forEach(cuccPayAddtionOfferVO -> cuccPayAddtionOfferVO.getOfferVOList()
                .removeIf(cuccOfferVO -> CuccPosServiceUtils.isOneOffAddtionalOffer(cuccOfferVO.getOfferId())));
        }
        return cuccPayAddtionOfferVOList;
    }

    private static void sortOfferList(List<CuccPayAddtionOfferVO> cuccPayAddtionOfferVOList) {
        for (CuccPayAddtionOfferVO cuccPayAddtionOfferVO : cuccPayAddtionOfferVOList) {
            List<CuccOfferVO> cuccOfferVOlist = cuccPayAddtionOfferVO.getOfferVOList();
            if (KiteListUtils.isNotEmpty(cuccOfferVOlist)) {
                Collections.sort(cuccOfferVOlist, new Comparator<CuccOfferVO>() {

                    @Override
                    public int compare(CuccOfferVO o1, CuccOfferVO o2) {
                        return o1.getOfferId().compareTo(o2.getOfferId());//根据第一个参数小于、等于或大于第二个参数分别返回负整数、零或正整数
                    }
                });
            }
        }
    }


    /**
     * 判断资费是否和关键属性相同
     *
     * @param cuccOfferVO
     * @param kiteProdInst
     * @param offerInstId
     * @param sceneInstId
     * @param staffId
     * @return true-匹配  false-不匹配
     */
    private boolean filterOfferVoByKeyAttr(CuccOfferVO cuccOfferVO, KiteProdInst kiteProdInst, String offerInstId, String sceneInstId, String staffId, List serviceOfferIdList, String offerid) {
        boolean resultCode = true;
        boolean resultflag = false;
        String catId = Optional.ofNullable(OfferCache.get(offerid)).map(Offer::getCateId).orElse("");
        String code = DcPublicCache.getPCode("20210903104801", catId);
        if (KiteStringUtils.equalsAny("T", code) && KiteListUtils.isNotEmpty(serviceOfferIdList)) {
            resultCode = false;
        }
        List<DcPublic> dpList = DcPublicCache.getByPkey("20210602110701", cuccOfferVO.getOfferId());
        if (KiteListUtils.isNotEmpty(dpList)) {//若存在配置则判断是否和关键实行一致 不存在返回true
            for (DcPublic dcPublic : dpList) {
                //dcPublic = dpList.get(0);offerid
                if (KiteStringUtils.isNotEmpty(dcPublic.getComments())) {
                    JSONObject cfgObj = JSON.parseObject(dcPublic.getComments());
                    for (JSONObject.Entry<String, Object> cfen : cfgObj.entrySet()) {
                        String[] cfenVal = JSON.parseArray(cfen.getValue().toString()).toArray(new String[]{});
                        boolean valFlag = false;
                        /*String[] cfenVal= cfen.getValue().toString().split(",");*/
                        for (String val : cfenVal) {
                            if (KiteStringUtils.equalsAny(kiteProdInst.getAttrValue(cfen.getKey()), val)) {
                                valFlag = true;
                                break;
                            }
                        }
                        if (KiteListUtils.isNotEmpty(serviceOfferIdList)) {
                            resultCode = false;
                            if (serviceOfferIdList.contains(dcPublic.getCodec())) {
                                if (((KiteStringUtils.equalsAny("*", cfenVal) && !kiteProdInst.getAttrValue(cfen.getKey()).isEmpty())) || valFlag) {
                                    resultflag = true;
                                } else {
                                    resultflag = false;
                                }
                            }
                        } else {
                            if (((KiteStringUtils.equalsAny("*", cfenVal) && kiteProdInst.getAttrValue(cfen.getKey()).isEmpty())) || !valFlag) {
                                resultCode = false;
                            }
                        }
                    }
                }
                if (resultCode || resultflag) {//若匹配成功
                    if (KiteStringUtils.equals("T", dcPublic.getPname()) && KiteListUtils.isEmpty(cuccOfferVO.getOfferInst())) {//默认选中、且尚未选中
                        String custId = KiteWebContext.getContext().getCustId();
                        OfferInstDTO offerInstDTO = operateSceneAdditionalOfferInstService
                            .addAdditionalOffer(sceneInstId, offerInstId, kiteProdInst.getProdInstId(), cuccOfferVO.getOfferId(), custId, staffId).getResultObject();

                        //处理可选包与产品实例之间的关系，因后续的明细处理事件的max不可控，可能导致没添加关系
                        OfferDetail additionalOfferDetail = OfferDetailCache.get(offerInstDTO.getOfferId()).stream().filter(offerDetail -> {
                            return offerDetail.getObjId().equals(kiteProdInst.getProdId());
                        }).findFirst().orElse(null);
                        if (!KiteObjectUtils.isEmpty(additionalOfferDetail)) {
                            sceneInstOperateService.addOfferObjInstRel(sceneInstId, InstType.ADDITIONAL_OFFER_INST, offerInstDTO.getOfferInstId(),
                                kiteProdInst.getInstType(), kiteProdInst.getProdInstId(), RelType.OFFER_OBJ_REL_TYPE_1000, ActionType.A,
                                additionalOfferDetail.getRoleId(), additionalOfferDetail.getDetailId(), KiteWebContext.getContext().getCustId());
                        }
                        KiteOfferInst additionalOfferInst = querySceneInstService.getOfferInst(custId, offerInstDTO.getOfferInstId());
                        cuccOfferVO.setOfferInst(Collections.singletonList(additionalOfferInst));
                    }
                    if (KiteStringUtils.equals("T", dcPublic.getCodeb())) {//是否必选
                        cuccOfferVO.setDisabled(true);
                    }
                    if (!resultCode && resultflag) {
                        resultCode = true;
                    }
                    return resultCode;//有一条配置匹配就返回
                }
            }
        }
        return resultCode;
    }

    /**
     * 根据标准月租计算配置费用
     *
     * @param payAddtionOfferVO 需要计算的资费
     * @param ratio             标准月租各资费比例
     * @return
     */
    private String count(CuccPayAddtionOfferVO payAddtionOfferVO, List<String> ratio) {
        BigDecimal sum = new BigDecimal(0);
        for (CuccOfferVO cuccOfferVO : payAddtionOfferVO.getOfferVOList()) {
            if (Objects.isNull(cuccOfferVO.getOfferInst())) {
                break;
            }
            if (null == cuccOfferVO.getOfferInst().get(0).getAttrMap().get("200001354")) {
                break;
            }
            String value = null == cuccOfferVO.getOfferInst().get(0).getAttrMap().get("200001354").getValue() ? "0" : cuccOfferVO.getOfferInst().get(0).getAttrMap().get("200001354").getValue();
            BigDecimal bigDecimal = new BigDecimal(value);
            sum = sum.add(bigDecimal);
        }
        if (sum.equals(BigDecimal.ZERO)) {
            for (CuccOfferVO cuccOfferVO : payAddtionOfferVO.getOfferVOList()) {
                if (Objects.isNull(cuccOfferVO.getOfferInst())) {
                    break;
                }
                if (null == cuccOfferVO.getOfferInst().get(0).getAttrMap().get("200001354")) {
                    break;
                }
                ratio.add("0");
            }
            return "";
        }
        for (CuccOfferVO cuccOfferVO : payAddtionOfferVO.getOfferVOList()) {
            if (Objects.isNull(cuccOfferVO.getOfferInst())) {
                break;
            }
            if (null == cuccOfferVO.getOfferInst().get(0).getAttrMap().get("200001354")) {
                break;
            }
            String value = null == cuccOfferVO.getOfferInst().get(0).getAttrMap().get("200001354").getValue() ? "0" : cuccOfferVO.getOfferInst().get(0).getAttrMap().get("200001354").getValue();
            BigDecimal bigDecimal = new BigDecimal(value);
            ratio.add(bigDecimal.divide(sum, 10, RoundingMode.HALF_UP).toString());
        }
        return sum.setScale(2).toString();
    }

    public static List<KiteAttr> dealLinkAttr(List<KiteAttr> kiteAttrList, String fieldName, String value) {
        Map<String, KiteAttr> instKite = kiteAttrList.stream().collect(Collectors.toMap(KiteAttr::getFieldName, KiteAttr -> KiteAttr));
        //首月收取方式
        KiteAttr FirstMonthkiteAttr = instKite.get("200000170");
        //生效时间
        KiteAttr starteDateKiteAttr = instKite.get(LocalKeyConsts.STARTING_DATE_FIELD_NAME);
        //失效时间
        KiteAttr endDateKiteAttr = instKite.get(LocalKeyConsts.END_DATE_FIELD_NAME);
        if (Objects.nonNull(FirstMonthkiteAttr) && FirstMonthkiteAttr.getAttrValues().size() > 0) {
            if (KiteStringUtils.isEqual(value, LocalKeyConsts.EFFECTIVE_IMMEDIATELY)) {
                //立即生效
                //生效时间当日0点生效，不可编辑
                if (Objects.nonNull(starteDateKiteAttr)) {
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    starteDateKiteAttr.setValue(DateFormatUtils.formatDate(KiteDateUtils.getStartOfDay(), DateFormatUtils.DATE_TIME_FORMAT));
                }

                //失效时间不可编辑
                if (Objects.nonNull(endDateKiteAttr)) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
            } else if (KiteStringUtils.isEqual(value, LocalKeyConsts.EFFECTIVE_NEXT_MONTH)) {
                //下月生效
                //生效时间次月0点生效，不可编辑
                if (Objects.nonNull(starteDateKiteAttr)) {
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    starteDateKiteAttr.setValue(DateFormatUtils.getFirstDayInNextMonth(DateFormatUtils.getFormatedDateTime(), DateFormatUtils.DATE_TIME_FORMAT));
                }
                //失效时间不可编辑
                if (Objects.nonNull(endDateKiteAttr)) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
            } else if (KiteStringUtils.isEqual(value, LocalKeyConsts.CUSTOM_VALIDATION)) {
                //自定义
                //生效时间当日0点生效，不可编辑
                if (Objects.nonNull(starteDateKiteAttr)) {
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_T);
                    starteDateKiteAttr.setValue(DateFormatUtils.formatDate(KiteDateUtils.getStartOfDay(), DateFormatUtils.DATE_TIME_FORMAT));
                }
                //失效时间不可编辑
                if (Objects.nonNull(endDateKiteAttr)) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_T);
                }
            } else if (KiteStringUtils.isEqual(value, LocalKeyConsts.EFFECTIVE_STARTING_TIME)) {
                //起租时间生效
                //生效时间0000-00-00 00:00:00，不可编辑
                if (Objects.nonNull(starteDateKiteAttr)) {
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    starteDateKiteAttr.setValue(DateFormatUtils.formatDate(KiteDateUtils.getStartOfDay(), DateFormatUtils.DATE_TIME_FORMAT));
                }
                //失效时间不可编辑
                if (Objects.nonNull(endDateKiteAttr)) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                }
            }
        } else {
            // 一次性费用
            //一次性费用，生效时间默认当天0点
            if (KiteStringUtils.isEqual(value, LocalKeyConsts.EFFECTIVE_IMMEDIATELY)) {
                //生效时间、失效时间，为当前操作日期的0点-23：59：59 ,生效时间、失效时间不可修改，置灰
                if (Objects.nonNull(starteDateKiteAttr)) {
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    starteDateKiteAttr.setValue(DateFormatUtils.formatDate(KiteDateUtils.getStartOfDay(), DateFormatUtils.DATE_TIME_FORMAT));
                }
                if (Objects.nonNull(endDateKiteAttr)) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    endDateKiteAttr.setValue(DateFormatUtils.formatDate(KiteDateUtils.getEndOfDay(), DateFormatUtils.DATE_TIME_FORMAT));
                    endDateKiteAttr.setValueDesc(DateFormatUtils.formatDate(KiteDateUtils.getEndOfDay(), DateFormatUtils.DATE_TIME_FORMAT));
                }
            } else if (KiteStringUtils.isEqual(value, LocalKeyConsts.EFFECTIVE_NEXT_MONTH)) {
                //下月生效
                String firstDayInNextMonth = DateFormatUtils.getFirstDayInNextMonth(DateFormatUtils.getFormatedDateTime(), DateFormatUtils.DATE_TIME_FORMAT);
                //失效时间不可编辑
                if (Objects.nonNull(endDateKiteAttr)) {
                    Date nextDate = DateFormatUtils.parseDateToFormat(firstDayInNextMonth, DateFormatUtils.DATE_TIME_FORMAT);
                    String endOfFirstDayInNextMonth = DateFormatUtils.formatDate(DateFormatUtils.getEndOfDay(nextDate), DateFormatUtils.DATE_TIME_FORMAT);
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    endDateKiteAttr.setValue(endOfFirstDayInNextMonth);
                    endDateKiteAttr.setValueDesc(endOfFirstDayInNextMonth);
                }
                //生效时间次月0点生效，不可编辑
                if (Objects.nonNull(starteDateKiteAttr)) {
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    starteDateKiteAttr.setValue(firstDayInNextMonth);
                }

            } else if (KiteStringUtils.isEqual(value, LocalKeyConsts.CUSTOM_VALIDATION)) {
                //生效时间、失效时间，为当前操作日期的0点-23：59：59 ,生效时间、失效时间不可修改，置灰
                if (Objects.nonNull(starteDateKiteAttr)) {
                    starteDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_T);
                    starteDateKiteAttr.setValue(DateFormatUtils.formatDate(KiteDateUtils.getStartOfDay(), DateFormatUtils.DATE_TIME_FORMAT));
                }
                if (Objects.nonNull(endDateKiteAttr)) {
                    endDateKiteAttr.setIsEdit(KeyConsts.IFTRUE_T);
                    endDateKiteAttr.setValue("2029-12-31 23:59:59");
                    endDateKiteAttr.setValueDesc("2029-12-31 23:59:59");
                }
            }
        }
        return instKite.entrySet().stream().map(e -> e.getValue()).sorted(Comparator.comparing(KiteAttr::getOrderId)).collect(Collectors.toList());
    }

    private void setOfferInst(String sceneInstId, String offerInstId, KiteProdInst kiteProdInst, Offer additionalOffer, String custId, String staffId, CuccOfferVO offerVO) {
        OfferInstDTO offerInstDTO = operateSceneAdditionalOfferInstService
            .addAdditionalOffer(sceneInstId, offerInstId, kiteProdInst.getProdInstId(), additionalOffer.getOfferId(), custId, staffId).getResultObject();

        //处理可选包与产品实例之间的关系，因后续的明细处理事件的max不可控，可能导致没添加关系
        OfferDetail additionalOfferDetail = OfferDetailCache.get(offerInstDTO.getOfferId()).stream().filter(offerDetail -> {
            return offerDetail.getObjId().equals(kiteProdInst.getProdId());
        }).findFirst().orElse(null);
        if (!KiteObjectUtils.isEmpty(additionalOfferDetail)) {

            sceneInstOperateService.addOfferObjInstRel(sceneInstId, InstType.ADDITIONAL_OFFER_INST, offerInstDTO.getOfferInstId(),
                kiteProdInst.getInstType(), kiteProdInst.getProdInstId(), RelType.OFFER_OBJ_REL_TYPE_1000, ActionType.A,
                additionalOfferDetail.getRoleId(), additionalOfferDetail.getDetailId(), KiteWebContext.getContext().getCustId());
        }
        KiteOfferInst additionalOfferInst = querySceneInstService.getOfferInst(custId, offerInstDTO.getOfferInstId());

        offerVO.setOfferInst(Collections.singletonList(additionalOfferInst));
    }

    private void filterFeeByAttr(List<OfferRelInfo> offerRelInfoList, List<KiteAttr> attrs, String offerId) {

        //            根据主产品关键属性过滤资费产品
        List<OfferFeeDiscntShowRule> feeDiscntShowRules = OfferFeeDiscntShowRuleCache.get(offerId);
        if (null != feeDiscntShowRules) {
            OfferFeeDiscntShowRule showRule = feeDiscntShowRules.stream().findFirst().orElse(null);
            if (null != feeDiscntShowRules && feeDiscntShowRules.size() > 0) {
                //        组装需要控制的资费
                Set<String> prods = new HashSet();
                showRule.getShowRules().stream().forEach(r->{
                    r.getShowProdIds().stream().forEach(jsonObject -> prods.add(jsonObject.getString("prodId")));
                });
                List<OfferRelInfo> control = offerRelInfoList.stream().filter(offerRelInfo -> prods.contains(offerRelInfo.getzOfferId())).collect(Collectors.toList());
                if (null != showRule) {
                    KiteAttr kiteAttr = attrs.stream().filter(attr -> KiteStringUtils.isEqual(attr.getFieldName(), showRule.getAttrCode())).findFirst().orElse(null);
                    if (null != showRule && null != kiteAttr && null != kiteAttr.getValue()) {
                        List<JSONObject> showProdIds = showRule.getShowRules().stream().filter(rule -> kiteAttr.getValue().equals(rule.getValueCode())).findFirst().map(ShowRule::getShowProdIds).orElse(Collections.EMPTY_LIST);
                        String prodIds = showProdIds.stream().map(jsonObject -> jsonObject.get("prodId").toString()).collect(Collectors.joining(","));
                        control =control.stream().filter(offerRelInfo -> !prodIds.contains(offerRelInfo.getzOfferId())).collect(Collectors.toList());
                        offerRelInfoList.removeAll(control);
                    }
                }
            }
        }
        List<DcPublic> dcPublics = DcPublicCache.getByPcode("2021110901", "feeShowRule", offerId);
        for (DcPublic dcPublic : dcPublics) {
            OfferRelInfo offerRelInfo = offerRelInfoList.stream().filter(offer -> offer.getzOfferId().equals(dcPublic.getCodec())).findFirst().orElse(null);
            KiteAttr kiteAttr = attrs.stream().filter(attr -> KiteStringUtils.isEqual(attr.getFieldName(), dcPublic.getCodea())).findFirst().orElse(null);
            if (null != offerRelInfo && null != kiteAttr) {
                if (!dcPublic.getCodeb().equals(kiteAttr.getValue())) {
                    offerRelInfoList.remove(offerRelInfo);
                }
            }
        }
    }
}
